/*eslint-disable padded-blocks*/
export default {
    install(Vue, opction) {
        Vue.filter('formTime', (value, value2, splitTime, subTime) => {
            let curLan = window.localStorage.getItem('globalLang') ? window.localStorage.getItem('globalLang') : 'cn';
            let nowData = value2 ? new Date(value2).getTime() : new Date().getTime();
            //

            //兼容App打包后的时间问题
            if (!value) {
                return;
            }
            let oldDate;
            if (new Date(value).toString() === 'Invalid Date') {
                let sub = value.replace(/-/g, '/');
                if (sub.includes('.')) {
                    sub = sub.substring(sub.indexOf('.'), 0);
                }
                oldDate = new Date(sub).getTime();
            } else {
                oldDate = new Date(value).getTime();
            }
            let getDate = Math.floor((nowData - oldDate) / 1000);
            //

            if (getDate < 1) {
                // getDate = 1;
            }
            //国际化时间
            if (curLan === 'en' && getDate === 1) {
                return `1 second`;
            } else if (getDate < 60) {
                if (curLan === 'cn') {
                    return `${getDate}秒前`; //+ this.$t('lab_time_tips_1')
                }
                if (curLan === 'hk') {
                    return `${getDate}秒前`; //+ this.$t('lab_time_tips_1')
                }
                if (curLan === 'en') {
                    return `${getDate} seconds`; //+ this.$t('lab_time_tips_1')
                }
            } else if ((getDate === 60 || getDate < 60 * 2) && curLan === 'en') {
                return `1 minute`; //+ this.$t('lab_time_tips_2')
            } else if (getDate < 60 * 60) {
                if (curLan === 'cn') {
                    return `${Math.floor(getDate / 60)}分钟前`; //+ this.$t('lab_time_tips_2')
                }
                if (curLan === 'hk') {
                    return `${Math.floor(getDate / 60)}分鐘前`; //+ this.$t('lab_time_tips_2')
                }
                if (curLan === 'en') {
                    return `${Math.floor(getDate / 60)} minutes`; //+ this.$t('lab_time_tips_2')
                }
            } else if ((getDate === 60 * 60 || getDate < 60 * 60 * 2) && curLan === 'en') {
                return `1 hour`; //+ this.$t('lab_time_tips_3')
            } else if (getDate < 24 * 60 * 60) {
                if (curLan === 'cn') {
                    return `${Math.floor(getDate / 60 / 60)}小时前`; //+ this.$t('lab_time_tips_3')
                }
                if (curLan === 'hk') {
                    return `${Math.floor(getDate / 60 / 60)}小時前`; //+ this.$t('lab_time_tips_3')
                }
                if (curLan === 'en') {
                    return `${Math.floor(getDate / 60 / 60)} hours`; //+ this.$t('lab_time_tips_3')
                }
            } else if (getDate <= 24 * 60 * 60 * 2) {
                if (curLan === 'en' || (getDate === 24 * 60 * 60 && getDate < 24 * 60 * 60 * 2)) {
                    return `1 day`; //+ this.$t('lab_time_tips_4')
                }
                if (curLan === 'cn') {
                    return `${Math.floor(getDate / 24 / 60 / 60)}天前`; //+ this.$t('lab_time_tips_4')
                }
                if (curLan === 'hk') {
                    return `${Math.floor(getDate / 24 / 60 / 60)}日前`; //+ this.$t('lab_time_tips_4')
                }
                if (curLan === 'en') {
                    return `${Math.floor(getDate / 24 / 60 / 60)} days`; //+ this.$t('lab_time_tips_4')
                }
            } else {
                if (splitTime) {
                    return value.split(' ')[0];
                }
                if (subTime) {
                    if (!(typeof (value) === 'string')) {
                        let tempDate = new Date(value);
                        return tempDate.getFullYear().toString() + '-' + this.dateStrHandle(tempDate.getMonth().toString()) + '-' + this.dateStrHandle(tempDate.getDay().toString());
                    }
                    return value.substring(0, value.indexOf(':', value.indexOf(':') + 1));
                }
                return value;
            }
        });
        Vue.mixin({
            data() {
                return {
                    appUrl: window.plus ? opction.getters.getAppUrl : '',
                    globalVideoFormat: ['mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac', 'MP4', 'WEBM', 'OGG', 'MP3', 'WAV', 'FLAC', 'AAC']
                };
            },
            methods: {
                wbEncryptor(id) { //id转化方法
                    let obj = {};
                    obj.CWN_ENC_KEY_1 = 157862245;
                    obj.CWN_ENC_KEY_2 = 32211;
                    obj.CWN_ENC_SEPARATOR = '_';
                    let encId;
                    obj.encrypt = function(id) {
                        encId = String(Number(id) + this.CWN_ENC_KEY_1) + this.CWN_ENC_SEPARATOR + String(this.CWN_ENC_KEY_1 - Number(id) - this.CWN_ENC_KEY_2);
                        return encId;
                    };
                    return obj.encrypt(id);
                },
                wbDecryption(id) { //id转化方法
                    let obj = {};
                    obj.CWN_ENC_KEY_1 = 157862245;
                    // obj.CWN_ENC_KEY_2 = 32211;
                    obj.nums = id.split('_');
                    if (obj.nums.length < 2) {
                        return id;
                    }
                    let entId;
                    obj.decryption = function(id) {
                        entId = Number(this.nums[0]) - this.CWN_ENC_KEY_1;
                        return entId;
                    };
                    return obj.decryption(id);
                },
                /**
                 * 上传分享图片
                 * @param event 当前元素
                 * @param type 规定当前请求类型（Img & Doc）
                 * @param callback 成功回调
                 * @param name 储存类型
                 */
                upFile(event, type, name, callback) {
                    if (!event.target.files[0]) {
                        return;
                    }
                    let upType;
                    if (type) {
                        upType = type;
                    } else {
                        let imgTypes = ['jpg', 'gif', 'jpeg', 'png'];
                        upType = imgTypes.indexOf(event.target.files[0].type.split('/')[1]) !== -1 ? 'Img' : 'Doc';
                    }
                    let formData = new FormData();
                    formData.append('file', event.target.files[0]);
                    formData.append('token', window.localStorage.getItem('token'));
                    formData.append('developer', 'mobile');
                    formData.append('uploadType', 'ajax');
                    this.$axios({
                        method: 'POST',
                        url: `/app/upload/mobile/${name}/${upType}`,
                        data: formData,
                        headers: {'Content-Type': 'multipart/form-data'}
                    }).then(res => {
                        if (upType === 'Img') {
                            callback(res.data, 'Img');
                        } else {
                            callback(res.data, 'Doc');
                        }
                    });
                },
                /**
                 * 删除上传的文件
                 * @param id 删除文件的id
                 * @param type  删除的类型
                 * @param callback
                 */
                deleteFile(id, type, callback) {
                    this.$axios({
                        method: 'POST',
                        url: `/app/upload/del/${id}`,
                        params: {
                            token: window.localStorage.getItem('token'),
                            developer: 'mobile'
                        }
                    }).then(res => {
                        if (type === 'Img') {
                            callback(res.data, 'Img');
                        } else {
                            callback(res.data, 'Dcc');
                        }
                    });
                },
                /**
                 * 兼容时间格式转换
                 * @param time
                 * @returns {number}
                 */
                conversionTime(time) {
                    if (!time) {
                        return false;
                    }
                    let nowTime;
                    if (new Date(time).toString() === 'Invalid Date') {
                        let sub = time.replace(/-/g, '/');
                        if (sub.includes('.')) {
                            sub = sub.substring(sub.indexOf('.'), 0);
                        }
                        nowTime = new Date(sub).getTime();
                    } else {
                        nowTime = new Date(time).getTime();
                    }
                    return nowTime;
                },
                downloadTask(_this, course, module) {
                    //视频下载
                    let url = this.appUrl + '/app/course/downloadByMod?modId=' + module.modId;
                    var dtask = this.$store.state.config.plus.downloader.createDownload(url, {method: 'get', filename: module.filename}, function(d, status) {});
                    module.dtask = dtask;
                    module.dtaskId = dtask.id;
                    _this.downloadTaskListener(dtask, _this, course, module);
                    //缓存取来
                    _this.$store.commit('addDownloadTaskCourse', course);
                    _this.$store.commit('putDownloadCourseModTask', {'key': module.modId, 'value': module});
                    //持久化存储
                    window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseTaskList', JSON.stringify(_this.$store.state.config.downloadCourseTaskList));
                    window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseModTask', JSON.stringify(_this.$store.state.config.downloadCourseModTask));
                },
                downloadTaskListener(dtask, _this, course, module) {
                    let taskLock = false;
                    let downloaded = false;
                    //下载任务初始化，添加事件监听
                    dtask.addEventListener('statechanged', function(task, status) {
                        //下载完成，因为存在一种情况，暂停/恢复过程中，未触发监听进入不了（task.state === 4）的方法
                        if (task.downloadedSize >= task.totalSize && module.getByte > 0 && task.totalSize > 0 && _this.$store.state.config.downloadCourseModTask.get(module.modId)) {
                            module.statusLabel = 'lab_downloaded';
                            module.status = 'completed';
                            _this.$store.commit('putDownloadCourseModTask', {'key': module.modId, 'value': module});
                            window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseTaskList', JSON.stringify(_this.$store.state.config.downloadCourseTaskList));
                            window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseModTask', JSON.stringify(_this.$store.state.config.downloadCourseModTask));
                            //开始正在等待列表的任务
                            if (!downloaded) {
                                downloaded = true;
                                setTimeout(() => {
                                    _this.startDownTask('start');
                                }, 1000);
                            }
                            return;
                        }
                        //状态码详情查阅https://www.html5plus.org/doc/zh_cn/downloader.html#plus.downloader.DownloadState
                        if (task.state === 0 || task.state === 1 || task.state === 2) {
                            //链接服务器，开始下载，新增加载任务
                        } else if (task.state === 3) {
                            setTimeout(() => {
                                if (taskLock) {
                                    return;
                                }
                                taskLock = true;
                                //接受数据，更新下载信息
                                module.isStartDtask = false;
                                module.totalByte = task.totalSize;
                                module.fileSize = (task.totalSize / 1024 / 1024).toFixed(2) + 'M';
                                module.getByte = task.downloadedSize;
                                if (module.startTime === '') {
                                    module.startTime = Date.parse(new Date());
                                }
                                module.endTime = Date.parse(new Date());
                                module.second = parseInt((module.endTime - module.startTime) / 1000);
                                //首次进入不显示下载的速率
                                if (module.second > 1) {
                                    module.statusLabel = 'lab_downloading';
                                    //计算下载速度
                                    let rate = parseInt((task.downloadedSize - module.preRate) / 2 / 1024);
                                    if (rate < 0) {
                                        //重建任务的时候速率为负数
                                        rate = 0;
                                    }
                                    if (rate < 1024) {
                                        module.rate = rate + 'KB/s';
                                    } else {
                                        module.rate = ((task.downloadedSize - module.preRate) / 2 / 1024 / 1024).toFixed(1) + 'MB/s';
                                    }
                                    //计算百分比
                                    module.percentage = parseInt((task.downloadedSize / task.totalSize) * 100) + '%';
                                }
                                module.preRate = task.downloadedSize;
                                _this.$store.commit('putDownloadCourseModTask', {'key': module.modId, 'value': module});
                                //持久化存储，存储下载任务到plus.storage
                                window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseTaskList', JSON.stringify(_this.$store.state.config.downloadCourseTaskList));
                                window.plus.storage.setItem(_this.$store.state.config.loginUser.usr_ent_id + '-downloadCourseModTask', JSON.stringify(_this.$store.state.config.downloadCourseModTask));
                                module.status = 'ing';
                                //释放锁
                                setTimeout(() => {
                                    taskLock = false;
                                }, 2000);
                            }, 0);
                        } else if (task.state === 4) {
                            //因为特殊原因，不在此处进行完成处理
                        }
                    }, false);
                },
                startDownTask(operation) {
                    //获取下载任务列表
                    let downloadCourseModTask = this.$store.state.config.downloadCourseModTask;
                    if (downloadCourseModTask) {
                        let task = null;
                        for (let i of downloadCourseModTask) {
                            let temp = i[1];
                            if (temp.status === 'ing') {
                                task = null;
                                return;
                            } else if (temp.status === 'waiting') {
                                if (task) {
                                    if (temp.updateTime < task.updateTime) {
                                        task = temp;
                                    }
                                } else {
                                    task = temp;
                                }
                            }
                        }
                        if (task) {
                            if (operation === 'resume' && !task.isStartDtask) {
                                task.statusLabel = 'lab_request_resource';
                                task.rate = '';
                                task.dtask.resume();
                            } else {
                                task.statusLabel = 'lab_request_resource';
                                this.$store.commit('putDownloadCourseModTask', {'key': task.modId, 'value': task});
                                setTimeout(() => {
                                    let modObj = this.$store.getters.getDownloadCourseModTask(task.modId);
                                    if (modObj.status === 'waiting') {
                                        modObj.status = 'ing';
                                        modObj.isStartDtask = false;
                                        modObj.dtask.start();
                                        this.$store.commit('putDownloadCourseModTask', {'key': modObj.modId, 'value': modObj});
                                    } else {
                                        this.startDownTask('start');
                                    }
                                }, 1000);
                            }
                        }
                    }
                },
                //暂停所有正在下载和等待的离线任务
                stopAllDownload() {
                    //获取下载任务列表
                    let downloadCourseModTask = this.$store.state.config.downloadCourseModTask;
                    for (let mapObj of downloadCourseModTask) {
                        let task = mapObj[1];
                        if (task.status === 'ing' || task.status === 'waiting') {
                            task.statusLabel = 'lab_pause';
                            task.status = 'pause';
                            task.rate = '';
                            task.dtask.pause();
                        }
                    }
                },
                //图片游览按返回键退出游览
                initPreviewRepair() {
                    //图片游览按返回键退出游览
                    this.$preview.on('imageLoadComplete', (e, item) => {
                        if (window.location.href.indexOf('&look') === -1) {
                            let _preview = this.$preview.self;
                            let lookUrl = window.location.href + '&look';
                            window.history.pushState(null, null, lookUrl);
                            _preview.listen('close', function() {
                                if (window.location.href.indexOf('&look') !== -1) {
                                    window.history.back();
                                }
                            });
                            window.onhashchange = function() {
                                if (_preview !== null && _preview !== undefined) {
                                    _preview.close();
                                    _preview = null;
                                }
                            };
                        }
                    });
                },
                //视频断点播放
                saveVideoProgress(key, time) {
                    //获取视频进度集合
                    let videoProgress = window.localStorage.getItem('videoProgress');
                    if (!videoProgress || videoProgress === null || videoProgress === 'null' || videoProgress === undefined || videoProgress === 'undefined') {
                        videoProgress = {};
                    } else {
                        videoProgress = JSON.parse(videoProgress);
                    }
                    //保存当前视频进度到集合对象
                    let usrEntId = window.localStorage.getItem('loginUser');
                    videoProgress[usrEntId + '-' + key] = time;
                    //保存到storage, .ios设备上无法重复setItem(),会出现诡异的QUOTA_EXCEEDED_ERR错误
                    window.localStorage.removeItem('videoProgress');
                    window.localStorage.setItem('videoProgress', JSON.stringify(videoProgress));
                },
                //视频断点播放
                getVideoProgress(key) {
                    //获取视频进度集合
                    let videoProgress = window.localStorage.getItem('videoProgress');
                    if (videoProgress && videoProgress !== null && videoProgress !== 'null' && videoProgress !== undefined && videoProgress !== 'undefined') {
                        //JSON字符串 => JSON对象
                        videoProgress = JSON.parse(videoProgress);
                        //获取视频进度
                        let usrEntId = window.localStorage.getItem('loginUser');
                        let time = videoProgress[usrEntId + '-' + key];
                        if (time === null || time === undefined) {
                            return 0;
                        }
                        return time;
                    }
                    return 0;
                },
                //视频断点播放
                breakpointplay(_this) {
                    var videoFormat = ['mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac', 'MP4', 'WEBM', 'OGG', 'MP3', 'WAV', 'FLAC', 'AAC'];
                    //断点播放
                    this.$nextTick(() => {
                        let count = 0;
                        let breakpointplay = setInterval(() => {
                            let src = _this.$refs.video ? _this.$refs.video.src : '';
                            let suffix = src.substring(src.lastIndexOf('.') + 1);
                            count++;//超过1分钟不执行
                            if (videoFormat.indexOf(suffix) !== -1 || count > 600) {
                                clearInterval(breakpointplay);
                                //idKey：自定义属性，用作区分相同外链的标识符
                                let idkey = _this.$refs.video.dataset.idkey;
                                //获取已看进度
                                let srcs = src.split('/');
                                let key = srcs[srcs.length - 1];
                                let time = this.getVideoProgress(idkey + '-' + key);
                                _this.$refs.video.currentTime = time;
                                let saveVideoProgressOpen = false;
                                if (_this.$refs.video.currentTime !== time) {
                                    //ios不同
                                    _this.$refs.video.addEventListener('canplay', () => {
                                        _this.$refs.video.currentTime = time;
                                        saveVideoProgressOpen = true;
                                    });
                                } else {
                                    saveVideoProgressOpen = true;
                                }
                                //执行自动保存视频进度程序,每3秒执行一次保存
                                let autoSaveProgress = setInterval(() => {
                                    if (_this.$refs.video && _this.$refs.video.src === src) {
                                        if (_this.$refs.video.currentTime !== time && saveVideoProgressOpen) {
                                            time = _this.$refs.video.currentTime;
                                            this.saveVideoProgress(idkey + '-' + key, time);
                                        }
                                    } else {
                                        clearInterval(autoSaveProgress);
                                    }
                                }, 3000);
                            }
                        }, 100);
                    });
                }
            },
            mounted() {
                document.addEventListener('plusready', () => {
                    if (window.plus) {
                        this.appUrl = this.$store.getters.getAppUrl;
                    }
                }, false);
            }
        });
        //yyyy-MM-dd HH:mm
        Vue.filter('substringTime', (value) => {
            if (value) {
                return value.substring(0, value.indexOf(':', value.indexOf(':') + 1));
            } else {
                return value;
            }
        });
        // 字符串转换 YYYY-MM-DD
        Vue.filter('formatDate', (time) => {
            if (time) {
                return time.slice(0, time.indexOf(' '));
            }
        });
        Vue.filter('yyyyMMdd', (value) => {
            if (value) {
                return value.substring(0, value.indexOf(' ') + 1);
            } else {
                return value;
            }
        });

        //yyyy-MM-dd HH:mm
        Vue.filter('conversionTime', (time) => {
            if (!time) {
                return '--';
            }
            // if (time.indexOf('-') > -1) {
            //     time = intiTime.replace(/-/g, '/');
            // }
            let intiTime = new Date(time);
            let leftYear = intiTime.getFullYear();
            let leftMonth = intiTime.getMonth();
            let leftDate = intiTime.getDate();
            let leftHours = intiTime.getHours();
            let leftMinutes = intiTime.getMinutes();
            if (leftMonth < 9) {
                leftMonth = '0' + (leftMonth + 1);
            } else {
                leftMonth = leftMonth + 1;
            };
            if (leftDate < 10) {
                leftDate = '0' + leftDate;
            };
            if (leftHours < 10) {
                leftHours = '0' + leftHours;
            };
            if (leftMinutes < 10) {
                leftMinutes = '0' + leftMinutes;
            };
            let date = leftYear + '-' + leftMonth + '-' + leftDate + ' ' + leftHours + ':' + leftMinutes;
            //适配ios11以上 时间 NaN 问题
            if (date.indexOf('-') > -1) {
                date = date.replace(/-/g, '/');
            }
            return date;
        });

        /**
         * 用户收藏
         * @params {string} type 当前类型
         * @params {number} id 用户id
         * */
        Vue.directive('collection', {
            bind(el, binding) {
                let isClick = binding.value.isClick;
                let time;
                el.onclick = () => {
                    clearTimeout(time);
                    time = setTimeout(() => {
                        if (isClick) {
                            Vue.prototype.$axios({
                                method: 'DELETE',
                                url: `/app/api/collect`,
                                params: {
                                    targetId: Number(binding.value.id),
                                    module: binding.value.type.toUpperCase()
                                }
                            }).then(res => {
                                if (res.data) {
                                    binding.value.count = binding.value.count > 1 ? binding.value.count - 1 : '0';
                                    el.innerHTML = Number(binding.value.count);
                                    isClick = !isClick;
                                    el.className = el.className.replace('cur', '');
                                }
                                if (binding.value.fn) {
                                    binding.value.fn('cancel', res.data);
                                }
                            }).catch(() => {
                                if (binding.value.fn) {
                                    binding.value.fn('error', null);
                                }
                            });
                        } else {
                            Vue.prototype.$axios({
                                method: 'POST',
                                url: `/app/api/collect`,
                                params: {
                                    targetId: Number(binding.value.id),
                                    module: binding.value.type.toUpperCase()
                                }
                            }).then(res => {
                                if (res.data) {
                                    el.className += ' cur';
                                    binding.value.count = (binding.value.count ? Number(binding.value.count) : 0) + 1;
                                    el.innerHTML = Number(binding.value.count);
                                    isClick = !isClick;
                                }
                                if (binding.value.fn) {
                                    binding.value.fn('add', res.data);
                                }
                            }).catch(() => {
                                if (binding.value.fn) {
                                    binding.value.fn('error', null);
                                }
                            });
                        }
                    }, 500);
                };
            }
        });
        /*点赞*/
        Vue.directive('like', {
            bind(el, binding) {
                let { isClick } = binding.value;
                let _this = this;
                let time;
                el.onclick = () => {
                    clearTimeout(time);
                    time = setTimeout(() => {
                        if (isClick) {
                            Vue.prototype.$axios({
                                method: 'POST',
                                url: `/app/api/valuation/like`,
                                data: {
                                    targetId: Number(binding.value.id),
                                    typeEnum: binding.value.type.toUpperCase(),
                                    isLike: false,
                                    isComment: false
                                }
                            }).then(res => {
                                el.className = el.className.replace('cur', '');
                                binding.value.count = binding.value.count > 1 ? binding.value.count - 1 : 0;
                                el.innerHTML = Number(binding.value.count);
                                isClick = !isClick;
                                if (binding.value.fn) {
                                    binding.value.fn('cancel', res.data);
                                }
                            });
                        } else {
                            Vue.prototype.$axios({
                                method: 'POST',
                                url: `/app/api/valuation/like`,
                                data: {
                                    targetId: Number(binding.value.id),
                                    typeEnum: binding.value.type.toUpperCase(),
                                    isLike: true,
                                    isComment: false
                                }
                            }).then(res => {
                                binding.value.count = (binding.value.count ? Number(binding.value.count) : 0) + 1;
                                el.innerHTML = Number(binding.value.count);
                                el.className += ' cur';
                                isClick = !isClick;
                                if (binding.value.fn) {
                                    binding.value.fn('add', res.data);
                                }
                            });
                        }
                    }, 500);
                };
            }
        });

    },
    dateStrHandle(val) {
        if (val.length < 2) {
            return '0' + val;
        }
        return val;
    }
};
